package com.jxit0573.android.lib.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author jia
 */
public class ThreadUtils {

    private static volatile ThreadUtils instance;

    private static ExecutorService executorService;

    private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();

    private ThreadUtils() {
    }

    public static ThreadUtils getInstance() {
        if (instance == null) {
            synchronized (ThreadUtils.class) {
                if (instance == null) {
                    instance = new ThreadUtils();
                }
            }
        }
        return instance;
    }

    public void execute(Runnable command) {
        ThreadFactory factory = new ThreadFactoryBuilder()
                .setNameFormat("pool-%d")
                .build();
        executorService = new ThreadPoolExecutor(NUMBER_OF_CORES,
                NUMBER_OF_CORES * 2,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1024),
                factory,
                new ThreadPoolExecutor.AbortPolicy());
        executorService.execute(command);
    }

    public void shutdownNow() {
        if (executorService != null) {
            executorService.shutdownNow();
        }
    }
}
